package com.sample.springbatch.job.sample.reader;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.database.JpaPagingItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Jpa 分页读取数据库
 * Created by zwg on 2017/8/8.
 */
@Component
public class RepayOrderJpaPagingItemReader<RepayOrderInfo> extends JpaPagingItemReader {

    Logger logger = LoggerFactory.getLogger(RepayOrderJpaPagingItemReader.class);

    @Autowired
    EntityManagerFactory entityManagerFactory;

    public RepayOrderJpaPagingItemReader() {
        setPageSize(1000);
        setQueryString("select new RepayOrderInfo(userId, productId, contractNo, amount, repayType, repayMethod) from RepayOrderInfo where createTime>:bussDate");
        Map<String, Object> params = new HashMap<>();
        try{
            params.put("bussDate", DateUtils.parseDate("2019-04-22 00:00:00", "YYYY-mm-dd hh:MM:ss"));
        }catch (Exception e){

        }

        setParameterValues(params);
        setSaveState(false);
    }


    @PostConstruct
    public void init(){
        setEntityManagerFactory(entityManagerFactory);
    }



    @Override
    @SuppressWarnings("unchecked")
    protected void doReadPage() {
        Long start = System.currentTimeMillis();
        super.doReadPage();
        logger.info("doReadPage time:{}",(System.currentTimeMillis()-start));
    }

}
